package com.servlet;

import com.dao.UserDao;
import com.dao.impl.Employee_infoDaoImpl;
import com.dao.impl.UserDaoImpl;
import com.entry.Employee_info;
import com.entry.User;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet(urlPatterns = "/login.do")
public class LoginServlet extends HttpServlet {
    @Override
    public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req,resp);
    }

    @Override
    public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");
        HttpSession session = req.getSession();
        JsonParser jParser = new JsonParser();
        JsonObject jt = (JsonObject) jParser.parse(req.getParameter("login"));//构造JsonObject对象
        String username = jt.get("username").getAsString();
        String userpass = jt.get("password").getAsString();
        String code = jt.get("code").getAsString();
        req.setAttribute("username",username);
        req.setAttribute("password",userpass);
        req.setAttribute("code",code);
        String mess= validateForm(username,userpass,code);
        UserDao userDao = new UserDaoImpl();
        User user = userDao.find(username,userpass);
        if(!"".equals(mess)){
            req.setAttribute("userLoginMess",mess);
            req.getRequestDispatcher("/index.jsp").forward(req,resp);
        }else{
            String sessioncode = session.getAttribute("sessioncode").toString();
            if(!code.equals(sessioncode)){
                req.setAttribute("userLoginMess","验证码错误！");
                req.getRequestDispatcher("/index.jsp").forward(req,resp);
            }else if(user == null){
                req.setAttribute("userLoginMess","用户名或者密码错误！");
                req.getRequestDispatcher("/index.jsp").forward(req,resp);
            }else{
                Employee_info employee_info = new Employee_infoDaoImpl().findUser(username);
                session.setAttribute("user",user);
                session.setAttribute("empl",employee_info);
                resp.sendRedirect(req.getContextPath() + "/Home.jsp");
            }
        }
    }
    private  String validateForm(String username,String userpass,String code){
        if(username == null || !username.matches("\\w{3,20}")){
            return "*用戶名不合法！";
        }else if(userpass == null || !userpass.matches("\\w{6,20}")){
            return "*密码不合法！";
        }else if(code == null || !code.matches("\\d{4}")){
            return "*验证码错误！";
        }
        return "";
    }
}
